﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin.Order;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Service.Interface.admin;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.admin
{
    [Inject_]
    public class Order_Service : Base_Service, I_Order_Service
    {
        private readonly Product_IOC _product_IOC;
        private readonly Order_IOC _order_IOC;
        private readonly Customer_IOC _customer_IOC;
        private readonly Login_IOC _login_IOC;
        private readonly Sys_IOC _sys_IOC;

        public Order_Service(Order_IOC order_IOC,
            Customer_IOC customer_IOC,
            Sys_IOC sys_IOC,
            Login_IOC login_IOC,
            Product_IOC product_IOC)
        {
            _product_IOC = product_IOC;
            _order_IOC = order_IOC;
            _customer_IOC = customer_IOC;
            _login_IOC = login_IOC;
            _sys_IOC = sys_IOC;
        }

       

        /// <summary>
        /// 获取订单
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Order(Fenye_Dto dto)
        {
            var data = await _order_IOC._orders_EFCore
                .GetAll(out int total,dto.page,dto.limit,false,o=>o.OCreateTime,(d=>d.OCustomerName.Contains(dto.key) || d.OId.Contains(dto.key)))
                .Select(d => new Order_Dto{
                orderNo=d.OId,
                amount=Convert.ToDouble(d.OTotalAmount),
                customerName=d.OCustomerName,
                payID=d.OPayType,
                status=d.OPayStatus==0?"待支付":"已支付",
                time=d.OCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                customerID=d.OCustomerId
                })
                .ToListAsync();
            var allproduct = _product_IOC._product_EFCore.GetAll().ToList();
            var allproductSpecs=_product_IOC._productSpecs_EFCore.GetAll().ToList();
            var allpackages=_product_IOC._productPackage_EFCore.GetAll().ToList();
           var all=_sys_IOC._sysDictionary_EFCore.GetAll().ToList();
            data.ForEach(d => {
                d.paymentMethod = all.Where(c => c.DId == d.payID).Select(c => c.DName).SingleOrDefault();
                // 找到当前订单的详情
                var orderDetails = _order_IOC._ordersDetails_EFCore.GetAll(c => c.OdOrderId == d.orderNo).SingleOrDefault();
                if (orderDetails == null) return; // 避免空引用异常

                var productNames = new List<string>();
                var packageNames = new List<string>();

                // 处理产品ID（分割后查询名称）
                if (!string.IsNullOrEmpty(orderDetails.OdProductId))
                {
                    //产品规格id
                    var productSpecsIds = orderDetails.OdProductId.Split(',').Where(id => !string.IsNullOrEmpty(id)).ToList();
                    //获取产品id
                    var productIds = allproductSpecs.Where(c => productSpecsIds.Contains(c.PsId)).Select(c => c.PsProductId).ToList();
                    productNames.AddRange(
                        allproduct.Where(p => productIds.Contains(p.PId))
                                  .Select(p => p.PName)
                                  .ToList()
                    );
                }

                // 处理套餐ID（分割后查询名称）
                if (!string.IsNullOrEmpty(orderDetails.OdPackageId))
                {
                    var packageIds = orderDetails.OdPackageId.Split(',').Where(id => !string.IsNullOrEmpty(id)).ToList();
                    packageNames.AddRange(
                        allpackages.Where(p => packageIds.Contains(p.PpId))
                                   .Select(p => p.PpName)
                                   .ToList()
                    );
                }

                // 合并产品和套餐名称（用逗号分隔）
                d.treatment = string.Join(",", productNames.Concat(packageNames));
            });

            return Get_Result(0, "ok", new { 
            data=data,
            total=total
            });
        }

        /// <summary>
        /// 获取所有的房间
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Room()
        {
            var data =await _order_IOC._room_EFCore.GetAll()
                .Select(d => new Room_Dto{
                id=d.RId,
                name=d.RName,
                currentOccupancy=d.RCurrentOccupancy,
                isBan=d.RIsBan,
                status=d.RStatus,
                totalBeds=d.RTotalBeds,
                createTime=d.RCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                updateTime=d.RUpdateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")
                }).ToListAsync();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取当前房间的客户
        /// </summary>
        /// <param name="roomID"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Room_Customer(string? roomID)
        {
            var customerID =await _order_IOC._orders_EFCore.GetAll(d => d.ORoomId == roomID && d.OOrderStatus==0).Select(d => d.OCustomerId).ToListAsync();
            var data =await _customer_IOC._customer_EFCore
                .GetAll(d => customerID.Contains(d.CId))
                .Select(d => new RoomCustomer_Dto{ 
                id=d.CId,
                name=d.CName,
                checkInTime=d.CCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                phone=d.CPhone

                }).ToListAsync();

            return Get_Result(0, "ok", data);
        }

        /// <summary>
        /// 获取订单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Single_Order(string? id)
        {
            var data = await _order_IOC._orders_EFCore.GetAll(d => d.OId == id)
                .Select(d => new OrderDetails_Dto {
                    id = d.OId,
                    totalAmount = (double?)d.OTotalAmount,
                    completeTime = d.OCompleteTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    createTime = d.OCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    customerName = d.OCustomerName,
                    customerPhone = d.OCustomerPhone,
                    employeeID=d.OEmployeeArtId,
                    employeeFrontId = d.OEmployeeFrontId,
                    orderStatus = d.OOrderStatus == 0 ? "进行中" : "已完成",
                    payID = d.OPayType,
                    payStatus = d.OPayStatus == 0 ? "待支付" : "已支付",
                    roomID = d.ORoomId,
                    orderDetails = new List<OrderProductDetails_Dto>()
                }).SingleAsync();
            var allemployee = _login_IOC._sysEmployee_EFCore.GetAll().ToList();
            var alldictionary = _sys_IOC._sysDictionary_EFCore.GetAll().ToList();
            var allroom = _order_IOC._room_EFCore.GetAll().ToList();
            var allProduct = _product_IOC._product_EFCore.GetAll().ToList(); // 产品表
            var allProductSpecs = _product_IOC._productSpecs_EFCore.GetAll().ToList(); // 产品规格表
            var allPackage = _product_IOC._productPackage_EFCore.GetAll().ToList(); // 套餐表
            data.employeeName = allemployee.FirstOrDefault(c => c.EId == data.employeeID)?.EName;
            data.employeeFrontName = allemployee.FirstOrDefault(c => c.EId == data.employeeFrontId)?.EName;
            data.roomName = allroom.FirstOrDefault(c => c.RId == data.roomID)?.RName;
            data.payType = alldictionary.FirstOrDefault(c => c.DId == data.payID)?.DName;

            // 订单服务详情
            var details = _order_IOC._ordersDetails_EFCore.GetAll(d => d.OdOrderId == data.id).SingleOrDefault();
            if (details != null)
            {
                // 处理产品规格
                var productSpecsList = new List<OrderProductDetails_Dto>();
                if (!string.IsNullOrEmpty(details.OdProductId))
                {
                    var productSpecsIds = details.OdProductId.Split(',').Where(id => !string.IsNullOrEmpty(id)).ToList();
                    var productSpecsEntities = allProductSpecs.Where(s => productSpecsIds.Contains(s.PsId)).ToList();
                    foreach (var spec in productSpecsEntities)
                    {
                        var product = allProduct.FirstOrDefault(p => p.PId == spec.PsProductId);
                        if (product != null)
                        {
                            productSpecsList.Add(new OrderProductDetails_Dto
                            {
                              
                                 productName= product.PName,
                                productSpecs = spec.PsName, // 假设规格表有名称字段 PsName
                                employeeName = data.employeeName, // 或从其他表获取理疗师
                                price = spec.PsPrice ?? 0 // 假设规格表有价格字段 PsPrice
                            });
                        }
                    }
                }

                // 处理套餐
                if (!string.IsNullOrEmpty(details.OdPackageId))
                {
                    var packageIds = details.OdPackageId.Split(',').Where(id => !string.IsNullOrEmpty(id)).ToList();
                    var packageEntities = allPackage.Where(p => packageIds.Contains(p.PpId)).ToList();
                    foreach (var pkg in packageEntities)
                    {
                        productSpecsList.Add(new OrderProductDetails_Dto
                        {
                           
                            productName = pkg.PpName, // 假设套餐表有名称字段 PpName
                            productSpecs = "套餐", // 可根据需求自定义
                            employeeName = data.employeeName,
                            price = (double?)pkg.PpPrice ?? 0 // 假设套餐表有价格字段 PpPrice
                        });
                    }
                }

                data.orderDetails = productSpecsList;
            }

            return Get_Result(0,"ok", data);
        }
    }
}
